package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"pay/dao"
	"pay/model"
	"pay/request"
)

func Login(c *gin.Context) {
	var data request.UserLogin
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10002,
			"msg":  "错误",
			"data": nil,
		})
		return
	}
	login, _ := dao.Login(data.Name)
	if login.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10003,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": login,
	})
}

func Register(c *gin.Context) {
	var data request.UserLogin
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  "错误",
			"data": err.Error(),
		})
		return
	}
	register, _ := dao.Register(data.Name, data.Password)
	log.Println(register)
	if register.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1003,
			"msg":  "注册失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"data": register,
	})
}

func List(c *gin.Context) {
	list, _ := dao.List()
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})
}

func ListWhere(c *gin.Context) {
	var data request.WhereList
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1002,
			"msg":  "错误",
			"data": err.Error(),
		})
		return
	}
	user := model.User{}
	d := dao.WhereList(&model.User{Name: data.Name}, &user)
	if d == false {
		c.JSON(http.StatusOK, gin.H{
			"code": 1003,
			"msg":  "查询失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "详情查询成功",
		"data": user,
	})
}
